package com.wenbo.fish.service;

import cn.hutool.http.Header;
import com.wenbo.fish.entity.CookieConstant;
import com.wenbo.fish.entity.SpiderInfo;
import com.wenbo.fish.enums.SpiderServiceEnum;
import com.wenbo.fish.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author changwenbo
 * @date 2024/12/31 14:54
 */
@Slf4j
@Component
public abstract class AbstractSpiderService implements SpiderService {
    public static final List EMPTY_LIST = Collections.emptyList();

    @Autowired
    public CookieConstant cookieConstant;

    @Override
    public List<SpiderInfo> spider() {
        String body = sendHttpRequest();
        if (StringUtils.isEmpty(body)) {
            return null;
        }

        return parseData(body);
    }

    protected abstract List<SpiderInfo> parseData(String body);

    public String sendHttpRequest() {
        SpiderServiceEnum serviceName = getServiceName();
        String url = serviceName.getUrl();

        Map<String, String> map = new HashMap<>();
        String cookie = cookieConstant.getCookie(serviceName);
        if (StringUtils.isNotEmpty(cookie)) {
            map.put(Header.COOKIE.getValue(), cookie);
        }

        return HttpUtils.get(url, map);
    }
}
